﻿using IRepository;
using IServices;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using YL.Core.Entity;
using YL.Core.Entity.Meter;
using YL.Utils.Extensions;
using YL.Utils.Json;
using YL.Utils.Table;

namespace Services
{
    public class Meter_DeviceAlarmHistoryServices : BaseServices<DeviceAlarmHistory>, IMeter_DeviceAlarmHistoryServices
    {
        private readonly SqlSugarClient _client;

        public Meter_DeviceAlarmHistoryServices(SqlSugarClient client, IMeter_DeviceAlarmHistoryRepository repository) : base(repository)
        {
            _client = client;
        }

        public string PageList(Bootstrap.BootstrapParams bootstrap,long userId)
        {
            int totalNumber = 0;
            if (bootstrap.offset != 0)
            {
                bootstrap.offset = bootstrap.offset / bootstrap.limit + 1;
            }

            var query = _client.Queryable<DeviceAlarmHistory,DeviceInfo,ClientInfo,AllLevelUserClientInfoView>
                ((s,c,u,w)=>new object[] { 
                JoinType.Left,s.DeviceId==c.DeviceId,
                JoinType.Left,c.ClientId==u.ClientId,
                JoinType.Left,u.ClientId==w.ClientId
                })
                .Where((s, c, u, w) =>w.UserId==userId)
                 .Select((s,c,u,w) => new
                 {
                     HistoryId = s.HistoryId.ToString(),
                     u.ClientName,
                     c.DeviceName,
                     s.AlarmEquip,
                     s.AlarmDetail,
                     s.AlarmType,
                     CreateDate = s.StartTime,
                     s.ConfirmTime,
                     s.ConfirmPerson,
                     s.ConfirmInfo,
                     s.EndTime
                 })
                 .MergeTable().Where((s) => s.HistoryId != null).OrderBy((s) => s.CreateDate, OrderByType.Desc);

            if (!bootstrap.search.IsEmpty())
            {
                query.Where((s) => s.ClientName.Contains(bootstrap.search));
            }

            if (!bootstrap.datemin.IsEmpty() && !bootstrap.datemax.IsEmpty())
            {
                query.Where(s => s.CreateDate > bootstrap.datemin.ToDateTimeB() && s.CreateDate <= bootstrap.datemax.ToDateTimeE());
            }
            if (bootstrap.order.Equals("desc", StringComparison.OrdinalIgnoreCase))
            {
                query.OrderBy($"MergeTable.{bootstrap.sort} desc");
            }
            else
            {
                query.OrderBy($"MergeTable.{bootstrap.sort} asc");
            }
            var list = query.ToPageList(bootstrap.offset, bootstrap.limit, ref totalNumber);
            return Bootstrap.GridData(list, totalNumber).JilToJson();
        }
    }
}
